package com.wjjun.base.utils

import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ItemTouchHelper.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wjjun.base.ui.viewmodel.BaseItemViewModel


class ItemDragCallback(val data: ObArrayList<BaseItemViewModel<*>>) : ItemTouchHelper.Callback() {

    /**
     * 规定可拖动的方向
     * 返回0表示不可拖动
     */
    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder
    ): Int {
        var dragFlags = 0
        val swipeFlags = 0

        val layoutManager = recyclerView.layoutManager
        if (layoutManager is GridLayoutManager) {
            dragFlags = (UP or DOWN or LEFT or RIGHT) //允许上下左右进行拖拽
        } else if (layoutManager is LinearLayoutManager) {
            if (layoutManager.orientation == LinearLayoutManager.VERTICAL) {
                dragFlags = (UP or DOWN)     // 允许上下拖拽
            } else {
                dragFlags = (LEFT or RIGHT)  // 允许左右拖拽
            }
        }
        return makeMovementFlags(dragFlags, swipeFlags)
    }

    /**
     * 当拖动的item移动到其他item的位置时会调用
     */
    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        //很奇怪,最后同样都是调用recyclerView的notifyItemMoved方法,上面的就是会出错.
//        data.move(viewHolder.adapterPosition, target.adapterPosition)
        data.moveNoneNotify(viewHolder.adapterPosition, target.adapterPosition)
        recyclerView.adapter?.notifyItemMoved(viewHolder.adapterPosition, target.adapterPosition)
        return true
    }

    /**
     * 当用户正在滑动子View时调用
     */
    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {

    }

    /**
     * 是否长按后触发拖动
     */
    override fun isLongPressDragEnabled(): Boolean {
        return super.isLongPressDragEnabled()
    }

    /**
     * 当被拖动的或者是被滑动的viewHolder改变时调用，actionState会返回当前ViewHolder的状态，有三个状态值。
     * action_state_swipe : 当View刚被滑动时返回
     * action_state_drag : 当View刚被拖动时返回
     * action_state_idle : 当View即没被拖动也没有被滑动时或者是滑动状态还没被触发时，返回这个状态
     * 在这里就可以进行拖动时候进行高亮显示,
     *
     */
    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        super.onSelectedChanged(viewHolder, actionState)
    }


    /**
     * 如果在onSelectedChanged中可以进行在view改变位置时更新UI，
     * 比如说进行高亮显示等，那么在clearView中是进行UI的复原，比如进行高亮显示的取消
     */
    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        super.clearView(recyclerView, viewHolder)
    }

}